<!DOCTYPE HTML>
<html>

<head>
	<link rel="bookmark"  type="image/x-icon"  href="/img/logo_miccall.png"/>
	<link rel="shortcut icon" href="/img/logo_miccall.png">
	
			    <title>
    Ame雨
    </title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="/amelin-ting/css/mic_main.css" />
    <link rel="stylesheet" href="/amelin-ting/css/dropdownMenu.css" />
    <meta name="keywords" content="Ame雨" />
    
    	<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
	 
    <noscript>
        <link rel="stylesheet" href="/amelin-ting/css/noscript.css" />
    </noscript>
    <style type="text/css">
        body:before {
          content: ' ';
          position: fixed;
          top: 0;
          background: url('/amelin-ting/img/bg.jpg') center 0 no-repeat;
          right: 0;
          bottom: 0;
          left: 0;
          background-size: cover; 
        }
    </style>

			    
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script async type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


    <script src="/amelin-ting/js/jquery.min.js"></script>
    <script src="/amelin-ting/js/jquery.scrollex.min.js"></script>
    <script src="/amelin-ting/js/jquery.scrolly.min.js"></script>
    <script src="/amelin-ting/js/skel.min.js"></script>
    <script src="/amelin-ting/js/util.js"></script>
    <script src="/amelin-ting/js/main.js"></script>
	
<meta name="generator" content="Hexo 5.4.0"></head>
    
		
<!-- Layouts -->



<!--  代码渲染  -->
<link rel="stylesheet" href="/css/prism_coy.css" />
<link rel="stylesheet" href="/css/typo.css" />
<!-- 文章页 -->
<body class="is-loading">
    <!-- Wrapper 外包 s-->
    <div id="wrapper" class="fade-in">
        <!-- Intro 头部显示 s -->
        <!-- Intro 头部显示 e -->
        <!-- Header 头部logo start -->
        <header id="header">
    <a href="/amelin-ting/" class="logo">Art Space</a>
</header>
        <!-- Nav 导航条 start -->
        <nav id="nav" class="special" >
            <ul class="menu links" >
			<!-- Homepage  主页  --> 
			<li >
	            <a href="/amelin-ting/" rel="nofollow">主页</a>
	        </li>
			<!-- categories_name  分类   --> 
	        
	        <li class="active">
	            <a href="#s1">分类</a>
	                    <ul class="submenu">
	                        <li>
	                        <a class="category-link" href="/amelin-ting/categories/Go/">Go</a></li><li><a class="category-link" href="/amelin-ting/categories/django/">django</a></li><li><a class="category-link" href="/amelin-ting/categories/drf/">drf</a></li><li><a class="category-link" href="/amelin-ting/categories/gin/">gin</a></li><li><a class="category-link" href="/amelin-ting/categories/go/">go</a></li><li><a class="category-link" href="/amelin-ting/categories/linux/">linux</a></li><li><a class="category-link" href="/amelin-ting/categories/mysql/">mysql</a></li><li><a class="category-link" href="/amelin-ting/categories/python/">python</a></li><li><a class="category-link" href="/amelin-ting/categories/%E5%86%85%E7%BD%91%E7%A9%BF%E9%80%8F/">内网穿透</a></li><li><a class="category-link" href="/amelin-ting/categories/%E5%89%8D%E7%AB%AF/">前端</a>
	                    </ul>
	        </li>
	        
	        <!-- archives  归档   --> 
	        
	        
		        <!-- Pages 自定义   -->
		        
		        <li>
		            <a href="/about/" title="简历">
		                简历
		            </a>
		        </li>
		        
		        <li>
		            <a href="/group/" title="团队">
		                团队
		            </a>
		        </li>
		        
		        <li>
		            <a href="/gallery/" title="图库">
		                图库
		            </a>
		        </li>
		        
		        <li>
		            <a href="/tag/" title="标签">
		                标签
		            </a>
		        </li>
		        


            </ul>
            <!-- icons 图标   -->
			<ul class="icons">
                    
                    <li>
                        <a title="github" href="https://github.com/miccall" target="_blank" rel="noopener">
                            <i class="icon fa fa-github"></i>
                        </a>
                    </li>
                    
                    <li>
                        <a title="500px" href="http://500px.com" target="_blank" rel="noopener">
                            <i class="icon fa fa-500px"></i>
                        </a>
                    </li>
                    
			</ul>
</nav>

        <div id="main" >
            <div class ="post_page_title_img" style="height: 25rem;background-image: url(https://img1.baidu.com/it/u=1846803631,2630758862&amp;fm=26&amp;fmt=auto);background-position: center; background-repeat:no-repeat; background-size:cover;-moz-background-size:cover;overflow:hidden;" >
                <a href="#" style="padding: 4rem 4rem 2rem 4rem ;"><h2 >gin-模板语法</h2></a>
            </div>
            <!-- Post -->
            <div class="typo" style="padding: 3rem;">
                <h2 id="一、gin"><a href="#一、gin" class="headerlink" title="一、gin"></a>一、gin</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Gin是一个用Go语言编写的web框架。它是一个类似于martini但拥有更好性能的API框架, 由于使用了httprouter，速度提高了近40倍。 如果你是性能和高效的追求者, 你会爱上Gin。</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// Go世界里最流行的Web框架，Github上有32K+star。 基于httprouter开发的Web框架。 中文文档齐全，简单易用的轻量级框架。</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">go</span> get -u github.com/gin-gonic/gin</span><br></pre></td></tr></table></figure>



<h2 id="二、gin简单操作"><a href="#二、gin简单操作" class="headerlink" title="二、gin简单操作"></a>二、gin简单操作</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;github.com/gin-gonic/gin&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sayHello</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">	c.JSON(<span class="number">200</span>, gin.H&#123;</span><br><span class="line">		<span class="string">&quot;msg&quot;</span>: <span class="string">&quot;hello world&quot;</span>,</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	engine := gin.Default() <span class="comment">// 创建一个默认的路由引擎</span></span><br><span class="line">	<span class="comment">// 指定用户是给GET请求访问/hello时，执行seyHello函数</span></span><br><span class="line">	engine.GET(<span class="string">&quot;/login&quot;</span>, sayHello)</span><br><span class="line">	<span class="comment">// 启动服务</span></span><br><span class="line">	engine.Run() <span class="comment">// 默认是8080端口</span></span><br><span class="line">	<span class="comment">// engine.Run(&quot;:9090&quot;)  可以这样修改端口</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="三、template初识"><a href="#三、template初识" class="headerlink" title="三、template初识"></a>三、template初识</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> Go语言内置了文本模板引擎text/template和用于HTML文档的html/template。它们的作用机制可以简单归纳如下：</span><br><span class="line"></span><br><span class="line">    <span class="number">1.1</span> 模板文件通常定义为.tmpl和.tpl为后缀（也可以使用其他的后缀），必须使用UTF8编码。</span><br><span class="line">    <span class="number">1.2</span> 模板文件中使用&#123;&#123;和&#125;&#125;包裹和标识需要传入的数据。</span><br><span class="line">    <span class="number">1.3</span> 传给模板这样的数据就可以通过点号（.）来访问，如果数据是复杂类型的数据，可以通过&#123; &#123; .FieldName &#125;&#125;来访问它的字段。</span><br><span class="line">    <span class="number">1.4</span> 除&#123;&#123;和&#125;&#125;包裹的内容外，其他内容均不做修改原样输出。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="number">2.</span> Go语言模板引擎的使用可以分为三部分：定义模板文件、解析模板文件和模板渲染.</span><br><span class="line"></span><br><span class="line">	<span class="number">2.1</span> 定义模板文件</span><br><span class="line">		其中，定义模板文件时需要我们按照相关语法规则去编写，后文会详细介绍。</span><br><span class="line"></span><br><span class="line">	<span class="number">2.2</span> 解析模板文件</span><br><span class="line">		上面定义好了模板文件之后，可以使用下面的常用方法去解析模板文件，得到模板对象：</span><br><span class="line">            <span class="function"><span class="keyword">func</span> <span class="params">(t *Template)</span> <span class="title">Parse</span><span class="params">(src <span class="keyword">string</span>)</span> <span class="params">(*Template, error)</span></span></span><br><span class="line">            <span class="function"><span class="keyword">func</span> <span class="title">ParseFiles</span><span class="params">(filenames ...<span class="keyword">string</span>)</span> <span class="params">(*Template, error)</span></span></span><br><span class="line">            <span class="function"><span class="keyword">func</span> <span class="title">ParseGlob</span><span class="params">(pattern <span class="keyword">string</span>)</span> <span class="params">(*Template, error)</span></span></span><br><span class="line">    <span class="comment">// 当然，你也可以使用func New(name string) *Template函数创建一个名为name的模板，然后对其调用上面的方法去解析模板字符串或模板文件。</span></span><br><span class="line"></span><br><span class="line">	<span class="number">3.3</span> 模板渲染</span><br><span class="line">        渲染模板简单来说就是使用数据去填充模板，当然实际上可能会复杂很多。</span><br><span class="line">            <span class="function"><span class="keyword">func</span> <span class="params">(t *Template)</span> <span class="title">Execute</span><span class="params">(wr io.Writer, data <span class="keyword">interface</span>&#123;&#125;)</span> <span class="title">error</span></span></span><br><span class="line">            <span class="function"><span class="keyword">func</span> <span class="params">(t *Template)</span> <span class="title">ExecuteTemplate</span><span class="params">(wr io.Writer, name <span class="keyword">string</span>, data <span class="keyword">interface</span>&#123;&#125;)</span> <span class="title">error</span></span></span><br><span class="line"></span><br><span class="line"><span class="number">3.</span> 代码演示</span><br><span class="line"><span class="comment">// hello.tmpl</span></span><br><span class="line">    &lt;!doctype html&gt;</span><br><span class="line">    &lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">        &lt;meta name=<span class="string">&quot;viewport&quot;</span></span><br><span class="line">              content=<span class="string">&quot;width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;</span>&gt;</span><br><span class="line">        &lt;meta http-equiv=<span class="string">&quot;X-UA-Compatible&quot;</span> content=<span class="string">&quot;ie=edge&quot;</span>&gt;</span><br><span class="line">        &lt;title&gt;Document&lt;/title&gt;</span><br><span class="line">    &lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &lt;p&gt;hello &#123;&#123; . &#125;&#125;&lt;/p&gt;</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">    &lt;/html&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">// main.go</span></span><br><span class="line">    <span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line">    <span class="keyword">import</span> (</span><br><span class="line">        <span class="string">&quot;fmt&quot;</span></span><br><span class="line">        <span class="string">&quot;html/template&quot;</span></span><br><span class="line">        <span class="string">&quot;net/http&quot;</span></span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">sayHello</span><span class="params">(w http.ResponseWriter, r *http.Request)</span></span> &#123;</span><br><span class="line">        <span class="comment">// 解析模板</span></span><br><span class="line">        t, err := template.ParseFiles(<span class="string">&quot;./hello.tmpl&quot;</span>) <span class="comment">// 这里一定要注意是build后文件的相对路径</span></span><br><span class="line">        <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">            fmt.Println(<span class="string">&quot;create template failed, err:&quot;</span>, err)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 渲染模板</span></span><br><span class="line">        name := <span class="string">&quot;Ame&quot;</span></span><br><span class="line">        err = t.Execute(w, name)</span><br><span class="line">        <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">            fmt.Println(<span class="string">&quot;render template failed, err:&quot;</span>, err)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        http.HandleFunc(<span class="string">&quot;/&quot;</span>, sayHello)</span><br><span class="line">        err := http.ListenAndServe(<span class="string">&quot;:9000&quot;</span>, <span class="literal">nil</span>)</span><br><span class="line">        <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">            fmt.Println(<span class="string">&quot;HTTP ser:&quot;</span>, err)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="四、模板语法详解"><a href="#四、模板语法详解" class="headerlink" title="四、模板语法详解"></a>四、模板语法详解</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> &#123;&#123;.&#125;&#125;</span><br><span class="line">    模板语法都包含在&#123;&#123;和&#125;&#125;中间，其中&#123;&#123;.&#125;&#125;中的点表示当前对象。</span><br><span class="line">    当我们传入一个结构体对象时，我们可以根据.来访问结构体的对应字段</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>注释</span><br><span class="line">    &#123;&#123;<span class="comment">/* a comment */</span>&#125;&#125;</span><br><span class="line">    注释，执行时会忽略。可以多行。注释不能嵌套，并且必须紧贴分界符始止。</span><br><span class="line"></span><br><span class="line"><span class="number">3.</span> pipeline</span><br><span class="line">    pipeline是指产生数据的操作。比如&#123;&#123;.&#125;&#125;、&#123;&#123;.Name&#125;&#125;等。Go的模板语法中支持使用管道符号|链接多个命令，用法和unix下的管道类似：|前面的命令会将运算结果(或返回值)传递给后一个命令的最后一个位置。</span><br><span class="line">    注意：并不是只有使用了|才是pipeline。Go的模板语法中，pipeline的概念是传递数据，只要能产生数据的，都是pipeline。</span><br><span class="line"></span><br><span class="line"><span class="number">4.</span> 变量</span><br><span class="line">    我们还可以在模板中声明变量，用来保存传入模板的数据或其他语句生成的结果。具体语法如下：</span><br><span class="line">    	$obj := &#123;&#123;.&#125;&#125;</span><br><span class="line">    其中$obj是变量的名字，在后续的代码中就可以使用该变量了。</span><br><span class="line"></span><br><span class="line"><span class="number">5.</span> 移除空格</span><br><span class="line">	有时候我们在使用模板语法的时候会不可避免的引入一下空格或者换行符，这样模板最终渲染出来的内容可能就和我们想的不一样，这个时候可以使用&#123;&#123;-语法去除模板内容左侧的所有空白符号， 使用-&#125;&#125;去除模板内容右侧的所有空白符号。</span><br><span class="line">	例如：</span><br><span class="line">        &#123;&#123;- .Name -&#125;&#125;</span><br><span class="line">        注意：-要紧挨&#123;&#123;和&#125;&#125;，同时与模板值之间需要使用空格分隔。</span><br><span class="line"></span><br><span class="line"><span class="number">6.</span> 条件判断</span><br><span class="line">    Go模板语法中的条件判断有以下几种:</span><br><span class="line">        &#123;&#123;<span class="keyword">if</span> pipeline&#125;&#125; T1 &#123;&#123;end&#125;&#125;</span><br><span class="line">        &#123;&#123;<span class="keyword">if</span> pipeline&#125;&#125; T1 &#123;&#123;<span class="keyword">else</span>&#125;&#125; T0 &#123;&#123;end&#125;&#125;</span><br><span class="line">        &#123;&#123;<span class="keyword">if</span> pipeline&#125;&#125; T1 &#123;&#123;<span class="keyword">else</span> <span class="keyword">if</span> pipeline&#125;&#125; T0 &#123;&#123;end&#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">7.</span> <span class="keyword">range</span></span><br><span class="line">    Go的模板语法中使用<span class="keyword">range</span>关键字进行遍历，有以下两种写法，其中pipeline的值必须是数组、切片、字典或者通道。</span><br><span class="line"></span><br><span class="line">    &#123;&#123;<span class="keyword">range</span> pipeline&#125;&#125; T1 &#123;&#123;end&#125;&#125;</span><br><span class="line">    如果pipeline的值其长度为<span class="number">0</span>，不会有任何输出</span><br><span class="line"></span><br><span class="line">    &#123;&#123;<span class="keyword">range</span> pipeline&#125;&#125; T1 &#123;&#123;<span class="keyword">else</span>&#125;&#125; T0 &#123;&#123;end&#125;&#125;</span><br><span class="line">    如果pipeline的值其长度为<span class="number">0</span>，则会执行T0。</span><br><span class="line"></span><br><span class="line"><span class="number">8.</span> with</span><br><span class="line">    &#123;&#123;with pipeline&#125;&#125; T1 &#123;&#123;end&#125;&#125;</span><br><span class="line">    如果pipeline为empty不产生输出，否则将dot设为pipeline的值并执行T1。不修改外面的dot。</span><br><span class="line"></span><br><span class="line">    &#123;&#123;with pipeline&#125;&#125; T1 &#123;&#123;<span class="keyword">else</span>&#125;&#125; T0 &#123;&#123;end&#125;&#125;</span><br><span class="line">    如果pipeline为empty，不改变dot并执行T0，否则dot设为pipeline的值并执行T1。</span><br><span class="line"></span><br><span class="line"><span class="number">9.</span> 预定义函数</span><br><span class="line">	执行模板时，函数从两个函数字典中查找：首先是模板函数字典，然后是全局函数字典。一般不在模板内定义函数，而是使用Funcs方法添加函数到模板里。</span><br><span class="line">	预定义的全局函数如下：</span><br><span class="line">        and</span><br><span class="line">            函数返回它的第一个empty参数或者最后一个参数；</span><br><span class="line">            就是说<span class="string">&quot;and x y&quot;</span>等价于<span class="string">&quot;if x then y else x&quot;</span>；所有参数都会执行；</span><br><span class="line">        or</span><br><span class="line">            返回第一个非empty参数或者最后一个参数；</span><br><span class="line">            亦即<span class="string">&quot;or x y&quot;</span>等价于<span class="string">&quot;if x then x else y&quot;</span>；所有参数都会执行；</span><br><span class="line">        not</span><br><span class="line">            返回它的单个参数的布尔值的否定</span><br><span class="line">        <span class="built_in">len</span></span><br><span class="line">            返回它的参数的整数类型长度</span><br><span class="line">        index</span><br><span class="line">            执行结果为第一个参数以剩下的参数为索引/键指向的值；</span><br><span class="line">            如<span class="string">&quot;index x 1 2 3&quot;</span>返回x[<span class="number">1</span>][<span class="number">2</span>][<span class="number">3</span>]的值；每个被索引的主体必须是数组、切片或者字典。</span><br><span class="line">        <span class="built_in">print</span></span><br><span class="line">            即fmt.Sprint</span><br><span class="line">        printf</span><br><span class="line">            即fmt.Sprintf</span><br><span class="line">        <span class="built_in">println</span></span><br><span class="line">            即fmt.Sprintln</span><br><span class="line">        html</span><br><span class="line">            返回与其参数的文本表示形式等效的转义HTML。</span><br><span class="line">            这个函数在html/template中不可用。</span><br><span class="line">        urlquery</span><br><span class="line">            以适合嵌入到网址查询中的形式返回其参数的文本表示的转义值。</span><br><span class="line">            这个函数在html/template中不可用。</span><br><span class="line">        js</span><br><span class="line">            返回与其参数的文本表示形式等效的转义JavaScript。</span><br><span class="line">        call</span><br><span class="line">            执行结果是调用第一个参数的返回值，该参数必须是函数类型，其余参数作为调用该函数的参数；</span><br><span class="line">            如<span class="string">&quot;call .X.Y 1 2&quot;</span>等价于<span class="keyword">go</span>语言里的dot.X.Y(<span class="number">1</span>, <span class="number">2</span>)；</span><br><span class="line">            其中Y是函数类型的字段或者字典的值，或者其他类似情况；</span><br><span class="line">            call的第一个参数的执行结果必须是函数类型的值（和预定义函数如<span class="built_in">print</span>明显不同）；</span><br><span class="line">            该函数类型值必须有<span class="number">1</span>到<span class="number">2</span>个返回值，如果有<span class="number">2</span>个则后一个必须是error接口类型；</span><br><span class="line">            如果有<span class="number">2</span>个返回值的方法返回的error非<span class="literal">nil</span>，模板执行会中断并返回给调用模板执行者该错误</span><br><span class="line"></span><br><span class="line"><span class="number">10.</span> 布尔函数会将任何类型的零值视为假，其余视为真。</span><br><span class="line"></span><br><span class="line">    下面是定义为函数的二元比较运算的集合：</span><br><span class="line"></span><br><span class="line">    eq      如果arg1 == arg2则返回真</span><br><span class="line">    ne      如果arg1 != arg2则返回真</span><br><span class="line">    lt      如果arg1 &lt; arg2则返回真</span><br><span class="line">    le      如果arg1 &lt;= arg2则返回真</span><br><span class="line">    gt      如果arg1 &gt; arg2则返回真</span><br><span class="line">    ge      如果arg1 &gt;= arg2则返回真</span><br><span class="line">    为了简化多参数相等检测，eq（只有eq）可以接受<span class="number">2</span>个或更多个参数，它会将第一个参数和其余参数依次比较，返回下式的结果：</span><br><span class="line"></span><br><span class="line">    &#123;&#123;eq arg1 arg2 arg3&#125;&#125;</span><br><span class="line">    比较函数只适用于基本类型（或重定义的基本类型，如”<span class="keyword">type</span> Celsius <span class="keyword">float32</span>”）。但是，整数和浮点数不能互相比较。</span><br><span class="line"></span><br><span class="line"><span class="number">11.</span> 自定义函数</span><br><span class="line">    Go的模板支持自定义函数。</span><br><span class="line">    &#123;&#123;kua .Name&#125;&#125;</span><br></pre></td></tr></table></figure>

<h2 id="五、模板嵌套"><a href="#五、模板嵌套" class="headerlink" title="五、模板嵌套"></a>五、模板嵌套</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">// 我们可以在template中嵌套其他的template。这个template可以是单独的文件，也可以是通过define定义的template。</span><br><span class="line"></span><br><span class="line">// t.tmpl</span><br><span class="line">    <span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;zh-CN&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;ie=edge&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>tmpl test<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">h1</span>&gt;</span>测试嵌套template语法<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">hr</span>&gt;</span></span><br><span class="line">        &#123;&#123;template &quot;ul.tmpl&quot;&#125;&#125;</span><br><span class="line">        <span class="tag">&lt;<span class="name">hr</span>&gt;</span></span><br><span class="line">        &#123;&#123;template &quot;ol.tmpl&quot;&#125;&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    &#123;&#123; define &quot;ol.tmpl&quot;&#125;&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">ol</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span>吃饭<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span>睡觉<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span>打豆豆<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ol</span>&gt;</span></span><br><span class="line">    &#123;&#123;end&#125;&#125;</span><br><span class="line"></span><br><span class="line">// ul.tmpl</span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span>注释<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span>日志<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span>测试<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"></span><br><span class="line">// gin_demo.go</span><br><span class="line">    func tmplDemo(w http.ResponseWriter, r *http.Request) &#123;</span><br><span class="line">        tmpl, err := template.ParseFiles(&quot;./t.tmpl&quot;, &quot;./ul.tmpl&quot;)</span><br><span class="line">        if err != nil &#123;</span><br><span class="line">            fmt.Println(&quot;create template failed, err:&quot;, err)</span><br><span class="line">            return</span><br><span class="line">        &#125;</span><br><span class="line">        user := UserInfo&#123;</span><br><span class="line">            Name:   &quot;Ame&quot;,</span><br><span class="line">            Gender: &quot;男&quot;,</span><br><span class="line">            Age:    18,</span><br><span class="line">        &#125;</span><br><span class="line">        tmpl.Execute(w, user)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">// 注意   在解析模板时，被嵌套的模板一定要在后面解析</span><br><span class="line">// 例如上面的示例中t.tmpl模板中嵌套了ul.tmpl，所以ul.tmpl要在t.tmpl后进行解析。</span><br></pre></td></tr></table></figure>

<h2 id="六、模板继承"><a href="#六、模板继承" class="headerlink" title="六、模板继承"></a>六、模板继承</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">// block是定义模板&#123;&#123;define &quot;name&quot;&#125;&#125; T1 &#123;&#123;end&#125;&#125;和执行&#123;&#123;template &quot;name&quot; pipeline&#125;&#125;缩写</span><br><span class="line">// 典型的用法是定义一组根模板，然后通过在其中重新定义块模板进行自定义</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">// 我们可以先创建一个base.tmpl文件</span><br><span class="line">在这个文件我们需要改动的地方写一个&#123;&#123; block &quot;名字&quot; .&#125;&#125; // 名字自定义 .是代表传入了数据</span><br><span class="line">    <span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;zh-CN&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>Go Templates<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;container-fluid&quot;</span>&gt;</span></span><br><span class="line">        &#123;&#123;block &quot;content&quot; . &#125;&#125;&#123;&#123;end&#125;&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">// index.tmpl 继承base</span><br><span class="line">    &#123;&#123; template &quot;base.tmpl&quot; &#125;&#125;</span><br><span class="line"></span><br><span class="line">    &#123;&#123; define &quot;content&quot; &#125;&#125;</span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span>&gt;</span>hello world!<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    &#123;&#123; end &#125;&#125;</span><br><span class="line"></span><br><span class="line">// 如果我们的模板名称冲突了，例如不同业务线下都定义了一个index.tmpl模板，我们可以通过下面两种方法来解决。</span><br><span class="line">    在模板文件开头使用&#123;&#123;define 模板名&#125;&#125;语句显式的为模板命名。</span><br><span class="line">    可以把模板文件存放在templates文件夹下面的不同目录中，然后使用template.ParseGlob(&quot;templates/**/*.tmpl&quot;)解析模板。</span><br></pre></td></tr></table></figure>

<h2 id="七、模板补充"><a href="#七、模板补充" class="headerlink" title="七、模板补充"></a>七、模板补充</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> </span><br><span class="line">	Go标准库的模板引擎使用的花括号&#123;&#123;和&#125;&#125;作为标识，而许多前端框架（如Vue和 AngularJS）也使用&#123;&#123;和&#125;&#125;作为标识符，所以当我们同时使用Go语言模板引擎和以上前端框架时就会出现冲突，这个时候我们需要修改标识符，修改前端的或者修改Go语言的。这里演示如何修改Go语言模板引擎默认的标识符：</span><br><span class="line"></span><br><span class="line">template.New(<span class="string">&quot;test&quot;</span>).Delims(<span class="string">&quot;&#123;[&quot;</span>, <span class="string">&quot;]&#125;&quot;</span>).ParseFiles(<span class="string">&quot;./t.tmpl&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span> text/template与html/tempalte的区别</span><br><span class="line"></span><br><span class="line">    html/template针对的是需要返回HTML内容的场景，在模板渲染过程中会对一些有风险的内容进行转义，以此来防范跨站脚本攻击。</span><br><span class="line">    例如，我定义下面的模板文件：</span><br><span class="line"></span><br><span class="line">    &lt;!DOCTYPE html&gt;</span><br><span class="line">    &lt;html lang=<span class="string">&quot;zh-CN&quot;</span>&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">        &lt;meta name=<span class="string">&quot;viewport&quot;</span> content=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span><br><span class="line">        &lt;meta http-equiv=<span class="string">&quot;X-UA-Compatible&quot;</span> content=<span class="string">&quot;ie=edge&quot;</span>&gt;</span><br><span class="line">        &lt;title&gt;Hello&lt;/title&gt;</span><br><span class="line">    &lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &#123;&#123;.&#125;&#125;</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">    &lt;/html&gt;</span><br><span class="line"></span><br><span class="line">    这个时候传入一段JS代码并使用html/template去渲染该文件，会在页面上显示出转义后的JS内容。 &lt;script&gt;alert(<span class="string">&#x27;嘿嘿嘿&#x27;</span>)&lt;/script&gt; 这就是html/template为我们做的事。</span><br><span class="line"></span><br><span class="line">    但是在某些场景下，我们如果相信用户输入的内容，不想转义的话，可以自行编写一个safe函数，手动返回一个template.HTML类型的内容。示例如下：</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">xss</span><span class="params">(w http.ResponseWriter, r *http.Request)</span></span>&#123;</span><br><span class="line">        tmpl,err := template.New(<span class="string">&quot;xss.tmpl&quot;</span>).Funcs(template.FuncMap&#123;</span><br><span class="line">            <span class="string">&quot;safe&quot;</span>: <span class="function"><span class="keyword">func</span><span class="params">(s <span class="keyword">string</span>)</span><span class="title">template</span>.<span class="title">HTML</span></span> &#123;</span><br><span class="line">                <span class="keyword">return</span> template.HTML(s)</span><br><span class="line">            &#125;,</span><br><span class="line">        &#125;).ParseFiles(<span class="string">&quot;./xss.tmpl&quot;</span>)</span><br><span class="line">        <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">            fmt.Println(<span class="string">&quot;create template failed, err:&quot;</span>, err)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        jsStr := <span class="string">`&lt;script&gt;alert(&#x27;嘿嘿嘿&#x27;)&lt;/script&gt;`</span></span><br><span class="line">        err = tmpl.Execute(w, jsStr)</span><br><span class="line">        <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">            fmt.Println(err)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">这样我们只需要在模板文件不需要转义的内容后面使用我们定义好的safe函数就可以了。</span><br><span class="line"></span><br><span class="line">	&#123;&#123; . | safe &#125;&#125;</span><br></pre></td></tr></table></figure>

<h2 id="八、gin框架模板渲染"><a href="#八、gin框架模板渲染" class="headerlink" title="八、gin框架模板渲染"></a>八、gin框架模板渲染</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 我们创建一个template文件夹，然后创建index.tmpl</span></span><br><span class="line">    &lt;!doctype html&gt;</span><br><span class="line">    &lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">        &lt;meta name=<span class="string">&quot;viewport&quot;</span></span><br><span class="line">              content=<span class="string">&quot;width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;</span>&gt;</span><br><span class="line">        &lt;meta http-equiv=<span class="string">&quot;X-UA-Compatible&quot;</span> content=<span class="string">&quot;ie=edge&quot;</span>&gt;</span><br><span class="line">        &lt;title&gt;Document&lt;/title&gt;</span><br><span class="line">    &lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &#123;&#123;.title&#125;&#125;</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">    &lt;/html&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Gin框架中使用LoadHTMLGlob()或者LoadHTMLFiles()方法进行HTML模板渲染。</span></span><br><span class="line">    <span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line">    <span class="keyword">import</span> (</span><br><span class="line">        <span class="string">&quot;github.com/gin-gonic/gin&quot;</span></span><br><span class="line">        <span class="string">&quot;net/http&quot;</span></span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">sayHello</span><span class="params">(w http.ResponseWriter, r *http.Request)</span></span> &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        r := gin.Default() <span class="comment">// 默认路由引擎</span></span><br><span class="line">        r.LoadHTMLFiles(<span class="string">&quot;template/index.tmpl&quot;</span>) <span class="comment">// 模板解析</span></span><br><span class="line"></span><br><span class="line">        r.GET(<span class="string">&quot;/index&quot;</span>, <span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">            c.HTML(http.StatusOK, <span class="string">&quot;index.tmpl&quot;</span>, gin.H&#123;</span><br><span class="line">                <span class="string">&quot;title&quot;</span>: <span class="string">&quot;Ame&quot;</span>,</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">        r.Run()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果在不同文件夹有两个同名tmpl文件，就得利用&#123;&#123;define &quot;posts/index.html&quot; .&#125;&#125; &#123;&#123;end&#125;&#125;来区别tmpl了</span></span><br><span class="line"><span class="comment">// 自定义函数模板 定义一个不转义相应内容的safe模板函数如下：</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        router := gin.Default()</span><br><span class="line">        router.SetFuncMap(template.FuncMap&#123;</span><br><span class="line">            <span class="string">&quot;safe&quot;</span>: <span class="function"><span class="keyword">func</span><span class="params">(str <span class="keyword">string</span>)</span> <span class="title">template</span>.<span class="title">HTML</span></span>&#123;</span><br><span class="line">                <span class="keyword">return</span> template.HTML(str)</span><br><span class="line">            &#125;,</span><br><span class="line">        &#125;)</span><br><span class="line">        router.LoadHTMLFiles(<span class="string">&quot;./index.tmpl&quot;</span>)</span><br><span class="line"></span><br><span class="line">        router.GET(<span class="string">&quot;/index&quot;</span>, <span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">            c.HTML(http.StatusOK, <span class="string">&quot;index.tmpl&quot;</span>, <span class="string">&quot;&lt;a href=&#x27;https://liwenzhou.com&#x27;&gt;李文周的博客&lt;/a&gt;&quot;</span>)</span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line">        router.Run(<span class="string">&quot;:8080&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">// tmpl文件内容如下</span></span><br><span class="line">    &lt;!DOCTYPE html&gt;</span><br><span class="line">    &lt;html lang=<span class="string">&quot;zh-CN&quot;</span>&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;title&gt;修改模板引擎的标识符&lt;/title&gt;</span><br><span class="line">    &lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">		&#123;&#123; . | safe &#125;&#125;</span><br><span class="line">	&lt;/div&gt;</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">    &lt;/html</span><br></pre></td></tr></table></figure>

<h2 id="九、配置静态文件"><a href="#九、配置静态文件" class="headerlink" title="九、配置静态文件"></a>九、配置静态文件</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 什么是静态文件 比如css js img之类的就是静态文件</span></span><br><span class="line"><span class="comment">// 我们在配置静态文件的时候，就可以建立一个static文件夹来存放他们</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// main.go</span></span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        r := gin.Default() <span class="comment">// 默认路由引擎</span></span><br><span class="line">        r.Static(<span class="string">&quot;/xxx&quot;</span>, <span class="string">&quot;./static&quot;</span>) <span class="comment">// 配置静态文件的动态路径</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// tmpl</span></span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;link rel=<span class="string">&quot;stylesheet&quot;</span> href=<span class="string">&quot;/xxx/css/index.css&quot;</span>&gt;</span><br><span class="line">    &lt;/head&gt;</span><br></pre></td></tr></table></figure>

<h2 id="十、gin框架的模板集成"><a href="#十、gin框架的模板集成" class="headerlink" title="十、gin框架的模板集成"></a>十、gin框架的模板集成</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Gin框架默认都是使用单模板，如果需要使用block template功能，可以通过&quot;github.com/gin-contrib/multitemplate&quot;库实现</span></span><br></pre></td></tr></table></figure>


            </div>

            <!-- Post Comments -->
            
    <!-- 使用 DISQUS_CLICK -->
<div id="disqus-comment">
    <div id="disqus_thread"></div>

<!-- add animation -->
<style>
	.disqus_click_btn {
            line-height: 30px;
            margin: 0;
            min-width: 50px;
            padding: 0 14px;
            display: inline-block;
            font-family: "Roboto", "Helvetica", "Arial", sans-serif;
            font-size: 14px;
            font-weight: 400;
            text-transform: uppercase;
            letter-spacing: 0;
            overflow: hidden;
            will-change: box-shadow;
            transition: box-shadow .2s cubic-bezier(.4, 0, 1, 1), background-color .2s cubic-bezier(.4, 0, .2, 1), color .2s cubic-bezier(.4, 0, .2, 1);
            outline: 0;
            cursor: pointer;
            text-decoration: none;
            text-align: center;
            vertical-align: middle;
            border: 0;
            background: rgba(158, 158, 158, .2);
            box-shadow: 0 2px 2px 0 rgba(0, 0, 0, .14), 0 3px 1px -2px rgba(0, 0, 0, .2), 0 1px 5px 0 rgba(0, 0, 0, .12);
            color: #fff;
            background-color: #7EC0EE;
            text-shadow: 0
        }
</style>
	
<div class="btn_click_load" id="disqus_bt"> 
    <button class="disqus_click_btn">点击查看评论</button>
</div>

<!--
<script type="text/javascript">
$('.btn_click_load').click(function() {
    /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
    var disqus_shortname = 'http-miccall-tech'; // required: replace example with your forum shortname

    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
      var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();

    document.getElementById('disqus_bt').style.display = "none";
});
</script>
-->
<script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'https://gitee.com/AmeX/amelin-ting.git/2020/06/04/Go---gin---%E6%A8%A1%E6%9D%BF%E8%AF%AD%E6%B3%95/';  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = 'https://gitee.com/AmeX/amelin-ting.git/2020/06/04/Go---gin---%E6%A8%A1%E6%9D%BF%E8%AF%AD%E6%B3%95/'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };
</script>

<script type="text/javascript">
    $('.btn_click_load').click(function() {  //click to load comments
        (function() { // DON'T EDIT BELOW THIS LINE
            var d = document;
            var s = d.createElement('script');
            s.src = '//http-miccall-tech.disqus.com/embed.js';
            s.setAttribute('data-timestamp', + new Date());
            (d.head || d.body).appendChild(s);
        })();
        $('.btn_click_load').css('display','none');
    });
</script>
</div>
<style>
    #disqus-comment{
        background-color: #eee;
        padding: 2pc;
    }
</style>


        </div>
        <!-- Copyright 版权 start -->
                <div id="copyright">
            <ul>
                <li>&copy;Powered By <a target="_blank" rel="noopener" href="https://hexo.io/zh-cn/" style="border-bottom: none;">hexo</a></li>
                <li>Design: <a target="_blank" rel="noopener" href="http://miccall.tech " style="border-bottom: none;">miccall</a></li>
            </ul>
            
                <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
			
        </div>
    </div>
</body>



 	
</html>
